package cn.com.dhc.danlu.activity.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;

import java.util.LinkedList;

import cn.com.dhc.danlu.R;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-09-20
 * Time: 10:44
 * Description: .....
 * ### fragment extends BaseV4Fragment & containerId must fl_fragment_container
 */
public abstract class DanluBaseFragmentActivity extends DanluBaseActivity {
    /**
     * list titles :different fragment show diff title
     */
    private final LinkedList<String> mTitles = new LinkedList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        setDefaultToolbarAttr();
        initArgs();
        if (null == savedInstanceState) {
            //防止fragment重叠
            addDefaultFragment(getDefaultFragment(), getDefaultTitle());
        }
        handleToolbarBackAction();
    }

    protected int getLayoutId() {
        return R.layout.dl_fragment_activity;
    }

    protected void setDefaultToolbarAttr() {

    }

    protected void initArgs() {
    }

    protected void addDefaultFragment(@NonNull Fragment fragment, String title) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_fragment_container, fragment, fragment.getClass().getSimpleName());
        transaction.addToBackStack("");
        transaction.commit();
        if (!TextUtils.isEmpty(title)) {
            mTitles.add(title);
        }
        mToolbar.setTitle(mTitles.get(0));
    }

    protected abstract Fragment getDefaultFragment();

    protected abstract String getDefaultTitle();

    private void handleToolbarBackAction() {
        mToolbar.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popFragment();
            }
        });
    }

    public void popFragment() {
        //获取fragment返回栈中的对象数量；
        int stackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
        if (stackEntryCount > 1) {
            //弹出fragment栈视图对象并且显示；
            getSupportFragmentManager().popBackStack();
            //改变标题栏；
            changeTitle();
        } else {
//            finish ();
            finishMySelf();
        }
    }

    protected void finishMySelf() {
        finish();
    }

    /**
     * 改变标题栏名称，传入返回栈元素数量；
     */
    protected void changeTitle() {
        //移除最后一个标题名；
        mTitles.removeLast();
        //获取最后一个元素，为标题名；
        String s = mTitles.get(mTitles.size() - 1);
        mToolbar.setTitle(s);
    }

    /**
     * 切换Fragment
     *
     * @param targetFragment
     *         需要切换至的目标Fragment
     * @param title
     *         切换后的Activity Title
     */
    protected void switchFragment(Fragment targetFragment, String title) {
        switchFragment(targetFragment, targetFragment.getClass().getSimpleName(), R.id.fl_fragment_container, title);
    }

    /**
     * @param targetFragment
     *         切换目标fragment
     */
    private void switchFragment(@NonNull Fragment targetFragment, String stackName, int fragmentLayoutId, final String title) {
        Fragment fragmentByTag = getSupportFragmentManager().findFragmentByTag(targetFragment.getClass().getSimpleName());//已加载的fragment；
        if (null != fragmentByTag && targetFragment == fragmentByTag) {
            return;       //传入的fragment与已加载的fragment相同，则返回；
        }
        getSupportFragmentManager().beginTransaction()
                                    /*.setCustomAnimations (R.anim.fragment_toleft_in, 0, 0, R.anim.fragment_toright_out)*/      //加入替换时的动画效果；
                .addToBackStack(stackName) // convenient muilt fragment pop
                .replace(fragmentLayoutId, targetFragment, targetFragment.getClass().getSimpleName()).commit();    //替换fragment；

        mToolbar.postDelayed(new Runnable() {       //加入延时操作；更改标题栏控件状态；
            @Override
            public void run() {
                mToolbar.setBackVisible(true);
                if (!TextUtils.isEmpty(title)) {
                    mToolbar.setTitle(title);
                }
            }
        }, 100);
        mTitles.add(title);     //将标题加入到LinkedList对象中；
    }

    protected void switchFragment(Fragment targetFragment, String stackName, String title) {
        switchFragment(targetFragment, stackName, R.id.fl_fragment_container, title);
    }

    @Override
    public void onBackPressed() {      //返回的操作；按返回键时调用；
        popFragment();
    }

    protected void clearSameTopStackFragment(String stackName) {
        int before = getSupportFragmentManager().getBackStackEntryCount();
        //弹出stankName之上的所以fragment
        getSupportFragmentManager().popBackStackImmediate(stackName, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        int now = getSupportFragmentManager().getBackStackEntryCount();
        int diff = before - now;
        int titleSize = mTitles.size();
        for (int i = titleSize - 1; i >= titleSize - diff; i--) {
            mTitles.remove(i);
        }
        String string = mTitles.get(mTitles.size() - 1);
        mToolbar.setTitle(string);
    }

}
